package org.zhouhe.modules.industry.service;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;
import org.zhouhe.base.BaseService;
import org.zhouhe.vo.Industry;

@Repository
@SuppressWarnings("unchecked")
public class IndustryService extends BaseService {
	public List<Industry> getIndustryTreeData(){
		List<Industry> list = dao.find("from Industry where industry is null order by orderId");
		return list;
	}
	public Industry getIndustryById(Integer industryId){
		return (Industry) dao.get(Industry.class, industryId);
	}
	public void saveIndustry(Industry industry){
		Industry parent = industry.getIndustry();
		if(parent != null && parent.getIndustryId() == null){
			industry.setIndustry(null);
		}
		industry.setStatus(1);
		dao.save(industry);
		String idPath = null;
		if(industry.getIndustry() == null){
			idPath = "|"+ industry.getIndustryId() + "|";
		}else{
			idPath = industry.getIndustry().getIdPath() + industry.getIndustryId() + "|";
		}
		industry.setIdPath(idPath);
		dao.update(industry);
	}
	public void deleteIndustry(Industry industry){
		Industry industryObj = this.getIndustryById(industry.getIndustryId());
		for(Industry indus : industryObj.getIndustries()){
			dao.delete(indus);
		}
		dao.delete(industryObj);
	}
	public void updateIndustry(Industry industry){
		Industry industryObj = this.getIndustryById(industry.getIndustryId());
		industryObj.setName(industry.getName());
		dao.update(industryObj);
	}
	public Integer getNextOrderId(final Integer parentId){
		Integer nextOrderId = dao.getHibernateTemplate().execute(new HibernateCallback<Integer>() {
			public Integer doInHibernate(Session session) throws HibernateException, SQLException {
				String sql = null;
				if(parentId == null){
					sql = "select max(order_id) from industry where parent_id is null";
				}else{
					sql = "select max(order_id) from industry where parent_id="+ parentId;
				}
				return (Integer) session.createSQLQuery(sql).uniqueResult();
			}
		});
		if(nextOrderId != null){
			nextOrderId++;
		}else{
			nextOrderId = 1;
		}
		return nextOrderId;
	}
	
	public void move(final Integer industryId, final boolean up){
		final Industry industry = this.getIndustryById(industryId);
		if(industry == null) return;
		dao.getHibernateTemplate().execute(new HibernateCallback<Object>() {
			public Integer doInHibernate(Session session) throws HibernateException, SQLException {
				// 按照显示顺序查询出行业
				List<Industry> list = null;
				if(industry.getIndustry() == null){
					list = session.createQuery("from Industry where industry is null order by orderId")
					.list();
				}else{
					list = session.createQuery("from Industry where industry=:parent order by orderId")
					.setEntity("parent", industry.getIndustry())
					.list();
				}
				
				// 查询当前操作的行业在list中的下标（如果数据库OrderId按规则正确排列，index最终值应该等于industry.getOrderId()）
				int index = 0;
				for(Industry indus:list){
					if(indus.getIndustryId().equals(industryId)){
						break;
					}else{
						index++;
					}
				}
				if(up){//向上移动：
					if(index > 0){
						Industry tmp = list.get(index);
						list.set(index, list.get(index-1));
						list.set(index-1, tmp);
					}else if(index == 0){
						Industry tmp = list.get(0);
						list.remove(0);
						list.add(tmp);
					}
				}else{//向下移动：
					if(index < list.size()-1){
						Industry tmp = list.get(index);
						list.set(index, list.get(index+1));
						list.set(index+1, tmp);
					}else if(index == list.size()-1){
						Industry tmp = list.get(index);
						list.remove(index);
						list.add(0, tmp);
					}
				}
				
				for(int i=0; i<list.size(); i++){
					Industry item = list.get(i);
					item.setOrderId(i);
					dao.save(item);
				}
				return null;
			}
		});
	}
	
}
